package com.emser.unc.client.presenter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import com.emser.unc.client.CloudMobile;
import com.emser.unc.client.helper.RPCCall;
import com.emser.unc.client.service.ReportsService;
import com.emser.unc.client.service.ReportsServiceAsync;
import com.emser.unc.client.view.BusyIndicatorView;
import com.emser.unc.serializable.NoSaleReportDTO;
import com.emser.unc.serializable.ResultDTO;
import com.emser.unc.serializable.UserAccountDTO;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.RangeChangeEvent;

public class NoSaleReportPresenter implements Presenter{
	private final Display display;
	private BusyIndicatorView busyIndicator;
	private ReportsServiceAsync reportService;
	private UserAccountDTO userA;
	private int start = 0;
	private ArrayList<String> cursors = new ArrayList<String>();
	private int pageNum;
	private String pageCursor;
	private ArrayList<Long> reportsIds;
	private int pageSize = CloudMobile.constants.pageSizeCP();
	
	
	public interface Display {	
	    Widget asWidget();
	    HasClickHandlers getRemoveButton();
	    MultiSelectionModel<NoSaleReportDTO> getSelectionModel();
		HasData<NoSaleReportDTO> getTable();
		void enableDelete(boolean enabled);
		void showWarning();
		void disableWarning();
		void enableBtnPopUpDelete(boolean enabled);
		HasClickHandlers getBtnPopUpDCancel();
	    HasClickHandlers getBtnPopUpDDelete();
		void showBusyIndicator();
		void hideBusyIndicator();
		void setPage(int page);
		int getPage();
	}
	
	public NoSaleReportPresenter(UserAccountDTO user,SimpleEventBus eventBus, Display display) {
		this.display = display;
		this.reportService = GWT.create(ReportsService.class);
		this.userA = user;
		cursors.add(null);
		bind();
		updateRowCount();
	}

	private void bind() {
		this.display.getRemoveButton().addClickHandler(new ClickHandler() {   
		      public void onClick(ClickEvent event) {
		    	  if(!display.getSelectionModel().getSelectedSet().isEmpty()){
		    		  display.enableDelete(false);
		    		  display.showWarning();
		    	  }
		      }
		});
		this.display.getTable().addRangeChangeHandler(new RangeChangeEvent.Handler() {
	        @Override
	        public void onRangeChange(RangeChangeEvent event) {
	        	doChangeRange();
	    }});
		this.display.getBtnPopUpDDelete().addClickHandler(new ClickHandler() {   
		      public void onClick(ClickEvent event) {
		    	  display.enableBtnPopUpDelete(false);
		    	  display.disableWarning();
		    	  doRemove();
		    	  display.enableBtnPopUpDelete(true);
		      }
		});
		this.display.getBtnPopUpDCancel().addClickHandler(new ClickHandler() {   
		      public void onClick(ClickEvent event) {
		    	  display.disableWarning();
		    	  display.enableDelete(true);
		      }
		});
	}

	protected void doChangeRange() {
		populateNoSaleReports();
	}
	
	private void doRemove() {
		final Set<NoSaleReportDTO> noSaleReports = this.display.getSelectionModel().getSelectedSet();
		Iterator<NoSaleReportDTO> iterator= noSaleReports.iterator();
		reportsIds = new ArrayList<Long>();
		if(noSaleReports.isEmpty()){
			display.enableDelete(true);
			return;
		}else{			
			display.showBusyIndicator();
			while(iterator.hasNext()){
				reportsIds.add(iterator.next().getIdReport());
			}
			new RPCCall<Boolean>(){
				@Override
				public void onFailure(Throwable caught) {
					display.hideBusyIndicator();	
					Window.alert(CloudMobile.constants.eDelete());
					display.enableDelete(true);
				}
				@Override
				public void onSuccess(Boolean result) {
					display.hideBusyIndicator();
					display.getSelectionModel().clear();
					if(result){
						cursors.clear();
						cursors.add(null);
						display.setPage(0);
						updateRowCount();
						display.enableDelete(true);
						
					}else
					{
						Window.alert(CloudMobile.constants.eServerDelete());
						display.enableDelete(true);
					}
				}
				@Override
				protected void callService(AsyncCallback<Boolean> cb) {
					reportService.deleteNoSaleReports(userA.getName(),reportsIds,cb);			
				}
			}.retry(3);	
		 }

	}
	
	private void populateNoSaleReports() {
		start = display.getTable().getVisibleRange().getStart();
		busyIndicator = new BusyIndicatorView(CloudMobile.constants.msjWorking());
		pageNum = display.getPage();
		try{
			pageCursor = cursors.get(pageNum);
		}
		catch(Exception e){
			pageCursor = null;
		}
		new RPCCall<ResultDTO<NoSaleReportDTO>>(){
			@Override
			public void onFailure(Throwable caught) {
				busyIndicator.hide();
				Window.alert(CloudMobile.constants.eGetNoSaleReports());			
			}
			@Override
			public void onSuccess(ResultDTO<NoSaleReportDTO> result) {
				busyIndicator.hide();
				try{
					pageCursor = cursors.get(pageNum+1);
				}
				catch(Exception e){
					pageCursor = null;
				}
				if(result != null){
					if(pageCursor == null)
						cursors.add(result.getCursorString());
				display.getTable().setRowData(start, result.getList());
				}
			}
			@Override
			protected void callService(AsyncCallback<ResultDTO<NoSaleReportDTO>> cb) {
				reportService.getSaleNoReports(pageCursor,pageSize,userA.getName(), cb);	
			}
		}.retry(3);
	}
	
	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
	}
	
	public void updateRowCount(){
		new RPCCall<Integer>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(CloudMobile.constants.eGetCountNoSaleReports());			
			}
			@Override
			public void onSuccess(Integer result) {
				display.getTable().setRowCount(result,true);
				if(result>0)
					populateNoSaleReports();
			}
			@Override
			protected void callService(AsyncCallback<Integer> cb) {
				reportService.getNoSaleReportCount(userA.getName(), cb);	
			}
		}.retry(3);
	}

}
